﻿using E_GovernmentSystem.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using SqlSugar;
using System.IO;
using System.Threading.Tasks;

namespace E_GovernmentSystem.Controllers
{
    public class NewCaseController : Controller
    {
        private readonly SqlSugarClient _db;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public NewCaseController(SqlSugarClient db, IWebHostEnvironment webHostEnvironment)
        {
            _db = db;
            _webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        //新建案件
        public IActionResult Add(basicinformationtable basic)
        {
            var result = _db.Insertable(basic).ExecuteCommand();
            return Json(result);
        }

        [HttpGet]
        public async Task<IActionResult> ExportFile()
        {
            var result = await GetTeacherName();

            string filename = "Table.xlsx";
            string filePath = Path.Combine(_webHostEnvironment.WebRootPath, filename);

            NPOI.XSSF.UserModel.XSSFWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();
            var sheet = book.CreateSheet();

            var headerRow = sheet.CreateRow(0);
            headerRow.CreateCell(0).SetCellValue("姓名");
            headerRow.CreateCell(1).SetCellValue("文本");
            headerRow.CreateCell(2).SetCellValue("数据源");

            var data = result;
            for (int i = 0; i < data.Count; i++)
            {
                var dataRow = sheet.CreateRow(i + 1);
                dataRow.CreateCell(0).SetCellValue(data[i].CallerName);
                dataRow.CreateCell(1).SetCellValue(data[i].CallerText);
                dataRow.CreateCell(2).SetCellValue(data[i].DataSources);
            }

            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                book.Write(fileStream); // 将工作簿写入文件流
            }

            var bytes = System.IO.File.ReadAllBytes(filePath);
            return File(bytes, "application/octet-stream", $"{System.DateTime.Now.ToString("yyyyMMdd")}.xlsx");
        }

        private async Task<List<basicinformationtable>> GetTeacherName()
        {
            var teachers = await _db.Queryable<basicinformationtable>().ToListAsync();
            return teachers;
        }
    }
}
